<template>
  <div>
    <div class="flex w-full">
      <div class="left w-[20%] min-w-[217px] min-h-[50vh] border-r-2px border-[#e4e7ed]"
        style="border-right: 1px solid #e4e7ed">
        <Left :list="leftList" />
      </div>
      <main class="flex-1">
        <Main v-model="mainList" @checkHandle="checkHandle" :checkDataId="checkDataId" @deleteHandle="deleteHandle"
          @copyHandle="copyHandle" />
      </main>
      <div class="right w-[20%]">
        <Right :value="checkData" @changeHandle="changeHandle" />
      </div>
    </div>
    <div>
      <Render :form-items="mainList" />
    </div>
  </div>
</template>
<script setup lang='ts'>
import { uniqueId } from './tool/index'
import Left from './left.vue'
import Main from './main.vue'
import Right from './right.vue'
import Render from './render.vue'

const leftList = [
  { label: '单行文本', id: 1, type: 'input' },
  { label: '多行文本', id: 1, type: 'textarea' },
  { label: '数字', id: 1, type: 'InputNumber' },
  { label: '选择框', id: 2, type: 'select' },
  {
    label: '单选',
    id: 3,
    type: 'radio',
    isGroup: true,
    options: [
      { label: '选项1', value: 1 },
      { label: '选项2', value: 2 },
    ],
    optionConfig: {
      border: true,
    },
  },
  {
    label: '多选',
    id: 4,
    type: 'checkbox',
    options: [
      { label: '选项1', value: 1 },
      { label: '选项2', value: 2 },
    ],
  },
  {
    label: '日历',
    id: 3,
    type: 'Datepicker',
  },
  { label: '自定义', id: 3, type: 'custom' },
]
const mainList = ref<any[]>([])

const checkDataId = ref<string | null>(null)
const checkData = computed(() => {
  const data = mainList.value.find((item) => item.id === checkDataId.value)
  return data || {}
})
function checkHandle(item: Record<string, any>) {
  checkDataId.value = item.id
}

function changeHandle(data: Record<string, any>) {
  const index = mainList.value.findIndex((item) => item.id === data.id)
  if (index !== -1) {
    mainList.value[index] = data
  }
}
function deleteHandle(data: Record<string, any>) {
  const index = mainList.value.findIndex((item) => item.id === data.id)
  if (index !== -1) {
    mainList.value.splice(index, 1)
  }
}
function copyHandle(data: Record<string, any>) {
  const newData = { ...data, id: uniqueId() }
  const index = mainList.value.findIndex((item) => item.id === data.id)
  console.log('index', index)
  if (index !== -1) {
    // 在下表index后插入
    mainList.value.splice(index + 1, 0, newData)
  } else {
    // 在最后插入
    mainList.value.push(newData)
  }
}
</script>
<style scoped lang='scss'>
</style>